<template>
  <div class="lyric">
    <div v-if="showLyric == false">
      <p>正在加载歌词...</p>
    </div>

    <div class="lyric-list" :style="{ top: lyricTop }" v-else>
      <p>{{ nowPlay.musicName }}</p>
      <p v-for="(item, index) in lyricList" :class="{ active: checkTime(item.lyrics, item.time, index) }">
        <span>{{ item.lyrics }}</span>
      </p>
    </div>
  </div>
</template>

<script setup>
import { reactive, toRefs, ref, onMounted } from 'vue'
import { storeToRefs } from 'pinia'
import { PlayStore } from '@/store/playlist'
import { computed } from '@vue/reactivity';

const playStore = PlayStore();

let { nowPlay, nowPlayTime, lyricList } = storeToRefs(playStore)

let showLyric = ref(false)
onMounted(() => {
  if (lyricList.value.length > 0) showLyric.value = true
})
/**
 * 定位歌词
 * pinia 当前播放的时间 > 歌词的初始时间  且  当前播放时间 < 下一句歌词的初始时间，就添加样式
 * 
 * time  当前歌词的时间
 * Index 当前下标
 */
let nowIndex = ref(0)
const checkTime = (item, time, index) => {
  // console.log(time);
  let inx;
  if (index < lyricList.value.length) inx = index + 1;
  let nextTime;
  if (lyricList.value[inx]) nextTime = lyricList.value[inx].time;

  // 提前200毫秒显示歌词
  if (nowPlayTime.value + 200 >= time && nowPlayTime.value + 200 <= nextTime && item != ' ') {
    nowIndex.value = index
    return true
  }
}

// 歌词高度
const lyricTop = computed(() => {
  return `-${50 * nowIndex.value / 75}rem`
})

</script>
  
<style lang='less' scoped>
.lyric {
  display: flex;
  justify-content: center;
  text-align: center;
  font-size: 30px;
  position: relative;
  overflow: hidden;

  p {
    margin: 20px 0;
    color: #ccc;

    &.active {
      color: #FFF !important;
      font-size: .8rem;
    }
  }
}

.lyric-list {
  position: absolute;
  top: 0;
  transition: all .3s;
  transform: translate(0, 0);
}
</style>